#include "widget.h"
#include "ui_widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QImage>
#include <QFileDialog>
#include <QDebug>
#include <QMouseEvent>
#include <QPainter>
#include <QVector>
#include <QMap>
#include <QColor>
#include <Qt>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->doubleSpinBox->setFixedWidth(70);
    ui->doubleSpinBox->setSingleStep(0.02);
    ui->lineEdit->setFixedWidth(100);
    imageLabel=new QLabel(this);
    imagescroll = new QScrollArea(this);
    imageLabel->setScaledContents(true);
    imagescroll->setGeometry(20,10,622,355);
    imagescroll->setWidget(imageLabel);
    processValue=50;
    scrollFactor=1;
    ui->perlabel->setText("100%");
    ui->progressBar->setValue(50);
    ui->progressBar->setMinimum(0);
    ui->progressBar->setMaximum(100);
    ui->subbtn->setEnabled(false);
    ui->plusbtn->setEnabled(false);
    ui->cancelbtn->setEnabled(false);
    this->setFixedSize(740,480);
    this->setWindowTitle("软件");
    ui->comboBox->addItem("红色");
    ui->comboBox->addItem("绿色");
    ui->comboBox->addItem("蓝色");
    ui->comboBox->addItem("白色");
    ui->comboBox->addItem("黑色");
    ispress=false;
    ispaint=true;
    connect(ui->loadImage,SIGNAL(clicked()),this,SLOT(openImage()));
    connect(ui->subbtn,SIGNAL(clicked()),this,SLOT(processbarvalue()));
    connect(ui->plusbtn,SIGNAL(clicked()),this,SLOT(processPlus()));
    connect(ui->restartpaint,SIGNAL(clicked()),this,SLOT(repaint()));
    connect(ui->closebtn,SIGNAL(clicked()),this,SLOT(autoclose()));
    connect(ui->calculatebtn,SIGNAL(clicked()),this,SLOT(calculateArea()));
    connect(ui->cancelbtn,SIGNAL(clicked()),this,SLOT(cancelPaint()));

}

Widget::~Widget()
{
    delete ui;
}
QPoint Widget::realPoint(QPoint ps){
    int X=ps.x()-imagescroll->geometry().x()-imageLabel->geometry().x();
    int Y=ps.y()-imagescroll->geometry().y()-imageLabel->geometry().y();
    QPoint rp(X,Y);
    return rp;
}

void Widget::openImage()
{
    //qDebug()<<"===============";
    clearElem();
    QString PATH=settings.value("filepath","0").toString();
    QString fileName;
    if (PATH=="0"){
        PATH=QDir::currentPath();
    }
    fileName = QFileDialog::getOpenFileName(this,
                                tr("Open File"), PATH);
    if (!fileName.isEmpty()) {
        QFileInfo fileinfo(fileName);
        settings.setValue("filepath",fileinfo.absolutePath());

        m_image.load(fileName);
        if (m_image.isNull()) {
            QMessageBox::information(this, tr("Image Viewer"),
                                     tr("Cannot load %1.").arg(fileName));
            return;
        }
        ui->subbtn->setEnabled(true);
        ui->plusbtn->setEnabled(true);
        ui->cancelbtn->setEnabled(true);
        ispaint=true;
        imageLabel->setPixmap(QPixmap::fromImage(m_image));
        imageLabel->adjustSize();
//        imageLabel->resize(scrollFactor * imageLabel->pixmap()->size());

       // qDebug()<<"Image:"<<m_image.size()<<" ,Label: "<<imageLabel->size();
    }
}

void Widget::processbarvalue(){
    if (processValue<=0){
        processValue=0;
        return;
    }
    ispaint=true;
    processValue-=1;
    clearElem();
    ui->perlabel->setText(QString::number(processValue+50)+"%");
    ui->progressBar->setValue(processValue);
    scrollFactor=(processValue+50.0)/100;
    scaleImage();
}

void Widget::processPlus(){
    if (processValue>=100){
        processValue=100;
        return;
    }
    processValue+=1;
    ispaint=true;
    clearElem();
    ui->perlabel->setText(QString::number(processValue+50)+"%");
    ui->progressBar->setValue(processValue);
    scrollFactor=(processValue+50.0)/100;
    scaleImage();
}

void Widget::scaleImage(){
    qDebug()<<scrollFactor;
    if(m_image.isNull()){
        return;
    }
   // imageLabel->resize(scrollFactor * imageLabel->pixmap()->size());
    QImage tmpimage=m_image.scaled(m_image.size()*scrollFactor,Qt::KeepAspectRatio);
    imageLabel->setPixmap(QPixmap::fromImage(tmpimage));
    imageLabel->adjustSize();
}

void Widget::repaint(){
    clearElem();
    ispaint=true;
    scaleImage();
}

void Widget::autoclose(){
    if (arrPoint.length()<3)
        return;

    drawLineTo(arrPoint.first(),arrPoint.last());
    ispaint=false;
}

void Widget::mousePressEvent(QMouseEvent *e){
    if (ispress&&ispaint){
        QPoint endpos=realPoint(e->pos());
        drawLineTo(lastPoint,endpos);
        lastPoint=endpos;
    }
}

bool isClickedTrue(QRect rect,QPoint ps){
    int x=rect.x();
    int y=rect.y();
    int x1=x+rect.width();
    int y1=y+rect.height();
    if(ps.x()>=x&&ps.y()>=y&&ps.x()<=x1&&ps.y()<=y1){
        return true;
    }else{
        return false;
    }
}

void Widget::mouseReleaseEvent(QMouseEvent *event){
    if (!ispaint){
        return;
    }
    if(!isClickedTrue(imagescroll->geometry(),event->pos()) || m_image.isNull()){
        return;
    }
    ispress=true;
    lastPoint=this->realPoint(event->pos());
    arrPoint.append(lastPoint);
    qDebug()<<lastPoint;

}

void Widget::drawLineTo(const QPoint &_lastPoint,const QPoint &_endPoint){
    if(m_image.isNull()){
        return;
     }
     QString type=ui->comboBox->currentText();
    if(type=="红色"){
        QImage tmp(imageLabel->pixmap()->toImage());
        QPainter painter(&tmp);
        painter.setPen(QPen(QColor(Qt::red)));
        painter.drawLine(_lastPoint, _endPoint);
        imageLabel->setPixmap(QPixmap::fromImage(tmp));

    }else if(type=="绿色"){
        QImage tmp(imageLabel->pixmap()->toImage());
        QPainter painter(&tmp);
        painter.setPen(QPen(QColor(Qt::green)));
        painter.drawLine(_lastPoint, _endPoint);
        imageLabel->setPixmap(QPixmap::fromImage(tmp));

     }else if(type=="蓝色"){
        QImage tmp(imageLabel->pixmap()->toImage());
        QPainter painter(&tmp);
        painter.setPen(QPen(QColor(Qt::blue)));
        painter.drawLine(_lastPoint, _endPoint);
        imageLabel->setPixmap(QPixmap::fromImage(tmp));

     }else if(type=="白色"){
        QImage tmp(imageLabel->pixmap()->toImage());
        QPainter painter(&tmp);
        painter.setPen(QPen(QColor(Qt::white)));
        painter.drawLine(_lastPoint, _endPoint);
        imageLabel->setPixmap(QPixmap::fromImage(tmp));
     }else if(type=="黑色"){
        QImage tmp(imageLabel->pixmap()->toImage());
        QPainter painter(&tmp);
        painter.setPen(QPen(QColor(Qt::black)));
        painter.drawLine(_lastPoint, _endPoint);
        imageLabel->setPixmap(QPixmap::fromImage(tmp));

     }

}



void Widget::clearElem(){
    ispress=false;
    arrPoint.clear();
}

void Widget::calculateArea(){
    double bili=ui->doubleSpinBox->value();
    double finalArea=PolygonArea(arrPoint)*bili;
    qDebug()<<finalArea;
    ui->lineEdit->setText(QString::number(finalArea));
}

void Widget::cancelPaint(){
    if(ispaint){
        ui->cancelbtn->setText("继续");
        ispaint=false;
    }else{
        ui->cancelbtn->setText("取消");
        ispaint=true;
    }
}

double Widget::PolygonArea(QVector<QPoint> polygon)
{
    int points=polygon.size();
    if (points<3) return 0;
    int *ppX=new int[points];
    int *ppY=new int[points];

    for (int i = 0; i < polygon.size(); ++i) {
        ppX[i]=polygon.at(i).x();
        ppY[i]=polygon.at(i).y();
       // qDebug()<<ppX[i]<<","<<ppY[i];
    }
    double area = 0;
    int  i, j=points-1  ;
    for (i=0; i<points; i++) {
      area+=(ppX[j]+ppX[i])*(ppY[j]-ppY[i]);
      j=i;
    }
    delete ppX;
    delete ppY;
    if (area<0){
        area=0-area;
    }
    return area / 2;
}
